﻿using HuaRunInterface.Comm;
using HuaRunLanYanInterface.Controllers;
using NPOI.SS.Formula.PTG;
using Utility;

namespace HuaRunLanYanInterface
{
    public class AITimer
    {
        Thread thread;
        public AITimer()
        {
            thread = new Thread(new ThreadStart(Excute));
            thread.IsBackground = true;
            thread.Start();
        }

        public static void Excute()
        {
            while (true)
            {

                string conn = Global.Configuration["ConnectionStrings:DDb"];
                using (Entity.DBContext context = Entity.BaseContext.CreateContext(conn))
                {
                    List<Entity.Models.ValveOperateInfo> records = context.valveOperateInfos.Where(p => p.SendFlag == 0).ToList();
                    WriteLog.WriteLogFile($"获取开关阀记录，条数：{records.Count},当前时间为：{DateTime.Now}");
                    foreach (var item in records)
                    {
                        string result = "";
                        result = Global.HttpIOTSend($"api/Conf/CtrlData/GetModel/{item.ctrl_id}", "");
                        WriteLog.WriteLogFile($"开关阀id:{item.ctrl_id};获取结果{result}");
                        if (!string.IsNullOrWhiteSpace(result))
                        {
                            Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(result);
                            if (obj["State"].ToString() == "success")//发送失败，全局程序继续发
                            {
                                CommandResponseModel mr = new CommandResponseModel();
                                mr.sequence = item.sequence;

                                CtrlReturnModel crm = obj["Data"].ToString().JSONStringToObject<CtrlReturnModel>();
                                mr.commandEndTime = crm.ctrl_timeout;
                                mr.msg = crm.ctrl_feedback_msg;
                                //0--等待发送
                                //1—已经发送   //物联网代表 放入缓存
                                //2—已经应答
                                //3—任务成功
                                //4—任务失败
                                //5—任务被取消
                                //6—任务超时
                                //7—发送数据失败
                                //99—其他错误
                                if (crm.ctrl_state == 0 || crm.ctrl_state == 1 || crm.ctrl_state == 2)
                                    continue;

                                if (crm.ctrl_state == 3)
                                {
                                    mr.success = true;
                                    mr.commandResult = "成功";
                                }
                                else
                                {
                                    mr.success = false;
                                    mr.commandResult = "失败";
                                }
                                string errMsg = "";
                                bool cmdRr = Global.CommonSend("eciot-openapi/cmdResponse", mr, ref errMsg);
                                WriteLog.WriteLogFile($"cmd Response : {cmdRr};msg:{errMsg}");
                                if (cmdRr)
                                {
                                    item.SendFlag = 1;
                                    context.valveOperateInfos.Update(item);
                                    int c = context.SaveChanges();
                                    if (c <= 0)
                                    {
                                        WriteLog.WriteExceptionFile($"修改开关阀发送结果值失败：{item.ID}");
                                    }
                                }
                            }
                        }
                    }
                }
                Thread.Sleep(new TimeSpan(0, 5, 0));
            }
        }
    }
    public class CtrlReturnModel
    {
        public int ctrl_id { get; set; }
        public int upper_ctrl_id { get; set; }
        public string company_no { get; set; }
        public string processor_name { get; set; }
        public string ctrl_define_no { get; set; }
        public string target_comm_no { get; set; }
        public int target_devtype { get; set; }
        public DateTime ctrl_time { get; set; }
        public DateTime ctrl_timeout { get; set; }
        public int ctrl_state { get; set; }
        public string ctrl_state_msg { get; set; }
        public string ctrl_feedback_msg { get; set; }
        public string ctrl_type { get; set; }
        public string ctrl_data { get; set; }
        public string return_data { get; set; }
        public int sync_flag { get; set; }
        public DateTime sync_time { get; set; }
        public string sync_msg { get; set; }
    }
}
